<?php
namespace mvc\web;

class Application
{
    public $controller;
    public $action;
    public static $container;

    public function run(array $config)
    {
        $this->initComponent($config);

        $this->parseRequest($config);
    }

    // 初始化组件
    public function initComponent($config)
    {
        $component = $config['component'];
        foreach ($component as $name => $object) {
            if(empty($object['class'])) {
                throw new \Exception("组件{$name}没有定义'classs'");
            }
            $instance = new $object['class'];
            $property = $object;
            unset($property['class']);
            foreach ($property as $param => $value) {
                $instance->$param = $value;
            }

            $className = lcfirst(substr($object['class'], strripos($object['class'],'\\')+1));

            self::$container[$className] = $instance;
        }
    }

    // 解析请求
    public function parseRequest($config)
    {
        $controller = isset($_GET['c']) ? $_GET['c'] : $config['defaultController'];
        $action = isset($_GET['a']) ? $_GET['a'] : $config['defaultAction'];

        $namespace = $config['namespace'];

        $fullName = $namespace . '\controllers\\' . ucfirst($controller) . 'Controller';

        $controllerInstance = new $fullName();
        $action = 'action' . ucfirst($action);
        if(!method_exists($controllerInstance, $action)) {
            throw new \Exception("没有找到{$action}方法");
        }
        echo $controllerInstance->$action();
    }

    public static function getComponent($component)
    {
        if(!isset(self::$container[$component])) {
            throw new \Exception('没有找到此组件');
        }

        return self::$container[$component];
    }
}